package com.h.forum.common.interceptor;

import com.h.forum.common.constant.Constants;
import com.h.forum.common.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 拦截器
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        // 从请求的 Header中进行查找token令牌
        String userToken = request.getHeader(Constants.HEADER_USER_TOKEN_KEY);

        log.info("从Header中获取token,url:{} ,userToken:{}",request.getRequestURI(),userToken);

        if (userToken == null) {
            response.setStatus(401);
            return false;
        }

        Claims claims = JWTUtil.parseJwt(userToken);
        if (claims == null) {
            response.setStatus(401);
            return false;
        }
        Constants.JWT = userToken;
        return true;
    }
}
